package com.xcm.util;

import com.google.common.collect.Maps;
import com.xcm.config.CustomProperties;
import com.xcm.constant.FileConstant;
import com.xcm.model.dto.BottomProgramDTO;
import com.xcm.model.dto.TopProgramDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

/**
 * 校验节目是否合法
 */
public class ValidateProgramJsonUtils {

	private static Logger logger = LoggerFactory.getLogger(ValidateProgramJsonUtils.class);
	@Autowired
	private static CustomProperties customProperties;

	public static Map<String, Integer> validateProgram(String xcVersion, List<TopProgramDTO> topList, List<BottomProgramDTO> bottomList) {
		//文件不存在列表、不合法视频文件（时长差的绝对值大于1）
		Map<String, Integer> illegalMsgMap = Maps.newHashMap();
		//创建文件临时存储目录
		String fileDownloadTempStoreDir = customProperties.getFileDownloadTempStoreDir();
		//系统分隔符
		String separator = File.separator;
		if (fileDownloadTempStoreDir.endsWith(separator)) {
			fileDownloadTempStoreDir = fileDownloadTempStoreDir + xcVersion;
		} else {
			fileDownloadTempStoreDir = fileDownloadTempStoreDir + separator + xcVersion;
		}
		File storeFileDir = new File(fileDownloadTempStoreDir);
		if (!storeFileDir.exists()) {
			storeFileDir.mkdirs();
		}
		// TODO: 2018/5/16  下载上屏文件 目前规定所有上屏文件都是avi格式的视频文件，如果以后有改动，请修改此处
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < topList.size(); i++) {
			TopProgramDTO topDTO = topList.get(i);
			String name = topDTO.getName();
			if (StringUtils.isBlank(name)) {
				continue;
			}
			//文件存储全路径
			sb.append(fileDownloadTempStoreDir).append(name).append(FileConstant.VIDEO_SUFFIX_AVI);
			String url = topDTO.getUrl();
			if (StringUtils.isNotBlank(url)) {
				try {
					FileUtils.downloadFileFromURL(url, sb.toString());
				} catch (IOException e) {
					e.printStackTrace();
					logger.error(name + FileConstant.VIDEO_SUFFIX_AVI + "不存在");
				}
			}
			sb.setLength(0);
		}
		//初始化sb长度为0
		// TODO: 2018/5/16  下载上屏文件 目前规定所有上下文件都是jpg格式的图片文件，如果以后有改动，请修改此处
		sb.setLength(0);
		//下载下屏文件
		for (int i = 0; i < bottomList.size(); i++) {
			BottomProgramDTO bottomDTO = bottomList.get(i);
			String name = bottomDTO.getName();
			if (StringUtils.isBlank(name)) {
				illegalMsgMap.put("图片文件名为空", FileConstant.FILE_NAME_IS_NULL);
				continue;
			}
			sb.append(fileDownloadTempStoreDir).append(name).append(FileConstant.PICTURE_SUFFIX_JPG);
			String url = bottomDTO.getUrl();
			if (StringUtils.isNotBlank(url)) {
				try {
					FileUtils.downloadFileFromURL(url,sb.toString());
				} catch (IOException e) {
					//如果文件不存在，添加到返回信息
					illegalMsgMap.put(name + FileConstant.VIDEO_SUFFIX_AVI, FileConstant.FILE_NOT_FOUND);
					e.printStackTrace();
					logger.error(name + FileConstant.VIDEO_SUFFIX_AVI + "不存在");
				}
			} else {
				illegalMsgMap.put(name, FileConstant.FILE_URL_IS_NULL);
			}
			sb.setLength(0);
		}
		//初始化sb长度为0
		sb.setLength(0);
		//校验视频文件（校验视频文件是否存在和视频时长）
		for (int i = 0; i < topList.size(); i++) {
			TopProgramDTO topDTO = topList.get(i);
			String name = topDTO.getName();
			if (StringUtils.isBlank(name)) {
				illegalMsgMap.put("视频文件名为空", FileConstant.FILE_NAME_IS_NULL);
				continue;
			}
			Integer duration = topDTO.getDuration();
			if (duration == null) {
				illegalMsgMap.put(name, FileConstant.VIDEO_DURATION_IS_NULL);
				continue;
			}
			sb.append(fileDownloadTempStoreDir).append(name).append(FileConstant.VIDEO_SUFFIX_AVI);
			File file = new File(sb.toString());
			if (file.exists()) {
				//读取视频时长
				double videoDuration = MultimediaUtils.readVideoDuration(file);
				//视频时长差（用读取到的视频时长减去原始视频时长）
				double diff = videoDuration - Double.parseDouble(String.valueOf(duration));
				//如果时长差的绝对值大于1，校验不通过
				DecimalFormat df = new DecimalFormat("0.00");
				String format = df.format(diff);
				double formatDouble = Double.parseDouble(format);
				if (Math.abs(formatDouble) > 1) {
					illegalMsgMap.put(name + FileConstant.VIDEO_SUFFIX_AVI, FileConstant.VIDEO_DURATION_ILLEGAL);
				}
			} else {
				illegalMsgMap.put(name + FileConstant.VIDEO_SUFFIX_AVI, FileConstant.FILE_NOT_FOUND);
			}
		}
		return illegalMsgMap;
	}
}
